package com.zzyl.nursing.service.impl;

import java.util.Date;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.utils.CodeGenerator;
import com.zzyl.utils.IDCardUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author laoYe
 * date 2025-10-21
 */

@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, elderDto.getIdCardNo()));
        if (null != elder) {
            if (elder.getStatus() == 4 || elder.getStatus() == 2 || elder.getStatus() == 1) {
                throw new RuntimeException("该老人已入住");
            }
        }

        //更新床位的状态, 得到更新结果，通过影响的记录行数判断，如果影响记录数>0则表示更新成功。乐观锁案例,利用数据库的行锁
        int count = bedMapper.updateBedStatus(dto.getCheckInConfigDto().getBedId());
        if (count == 0) {
            throw new RuntimeException("该床位已被入住");
        }

        //老人未入住且床位为空，另写方法修改或增加老人
        Elder saveElder = saveOrUpdateElder(dto,elder);
        //根据老人信息添加入住信息
        CheckIn checkIn = saveOrUpdateCheckIn(dto, saveElder);
        //根据入住信息添加合同信息
        saveOrUpdateContract(dto, checkIn);
        //根据入住信息添加配置信息
        saveOrUpdateConfig(dto, checkIn);

    }


    private Elder saveOrUpdateElder(CheckInApplyDto dto, Elder elder) {
        Elder saveElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        saveElder.setStatus(1);
        Integer bedId = dto.getCheckInConfigDto().getBedId();
        saveElder.setBedId(Long.valueOf(bedId));
        saveElder.setBedNumber(bedMapper.selectById(bedId).getBedNumber());
        //补充表中信息
        //判断老人是否为已经存在
        if (null != elder) {
            saveElder.setId(elder.getId());
            saveElder.setUpdateTime(DateUtils.getNowDate());
            elderMapper.updateById(saveElder);
        } else {
            saveElder.setCreateTime(DateUtils.getNowDate());
            elderMapper.insert(saveElder);
        }
        return saveElder;
    }

    private CheckIn saveOrUpdateCheckIn(CheckInApplyDto dto, Elder saveElder) {
        CheckIn checkIn = new CheckIn();
        //调整老人相关信息
        checkIn.setElderId(saveElder.getId());
        checkIn.setElderName(saveElder.getName());
        checkIn.setIdCardNo(saveElder.getIdCardNo());

        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());

        //床位信息
        checkIn.setBedNumber(saveElder.getBedNumber());
        checkIn.setStatus(0);

        //创建入住信息
        checkIn.setCreateTime(new Date());
        checkIn.setUpdateTime(checkIn.getCreateTime());

        //将家属信息转化为字符串填入备注
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        save(checkIn);
        return checkIn;
    }

    private void saveOrUpdateContract(CheckInApplyDto dto, CheckIn checkIn) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setCheckInId(checkIn.getId());
        contract.setElderId(checkIn.getElderId());


        contract.setContractNumber(CodeGenerator.generateContractNumber());

        contract.setElderName(checkIn.getElderName());

        contract.setStartDate(checkIn.getStartDate());
        contract.setEndDate(checkIn.getEndDate());

        contract.setStatus(0);
        contract.setCreateTime(new Date());
        contract.setUpdateTime(contract.getCreateTime());

        contractMapper.insert(contract);
    }

    private void saveOrUpdateConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig config = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        config.setCheckInId(checkIn.getId());
        config.setCreateTime(new Date());
        config.setUpdateTime(config.getCreateTime());
        checkInConfigMapper.insert(config);
    }

    @Override
    public CheckInDetailVo selectAllById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //获取合同信息
        Contract contract = contractMapper.selectContractByCheck_Id(id);
        checkInDetailVo.setContract(contract);

        //获取家属信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        checkInDetailVo.setElderFamilyVoList(JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class));

        //获取老人信息
        CheckInElderVo elder = BeanUtil.toBean(elderMapper.selectById(checkIn.getElderId()), CheckInElderVo.class);
        elder.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(elder);

        //获取入住配置信息
        checkInDetailVo.setCheckInConfigVo(checkInConfigMapper.selectCheckInConfigVoById(id));
        return checkInDetailVo;
    }

}
